package com.arlen.service.impl;

import com.arlen.mapper.LoginMapper;
import com.arlen.pojo.TUser;
import com.arlen.service.LoginService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, TUser> implements LoginService  {

    @Autowired
    PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null){
            return  null;
        }
//        LambdaQueryWrapper<TUser> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq("user_name",username);
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<TUser>();
        queryWrapper.eq("user_name",username);
        TUser tUser = getOne(queryWrapper);
        if (tUser == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("def");
        if (username.equals("arlen")){
            List<GrantedAuthority> list = AuthorityUtils.commaSeparatedStringToAuthorityList("add,admin,ROLE_arlen");
            authorities.addAll(list);
        }

         return new User(username,tUser.getPassWord(),authorities);
    }
}
